import { Component, OnInit, NgZone } from '@angular/core';
import { ActivatedRoute, Params, Router, NavigationEnd } from '@angular/router';

import { CudTableService } from 'app/public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../../public/serve/remove-table/remove-table.service';
import { InitService } from '../../../../public/serve/init/init.service';
import { TreeNode } from '../../../../public/common/api';
import { Service } from '../../../../server/server';

import { taskAddEimt } from "../../product-task-list";
import { appProductUrl } from '../../../product.url';
import { product,exportRefreshTable } from '../../../product.data';
import {appThemeTagUrl} from '../../../../system/theme-tag/theme-tag.url';
declare var $:any;
@Component({
    selector: 'app-product-indexing-task-list-table',
    templateUrl: './product-indexing-task-list-table.component.html',
    styleUrls: ['./product-indexing-task-list-table.component.css']
})
export class ProductIndexingTaskListTableComponent implements OnInit {
    total: number = 0;
    naturalNum: number = 0;
    tabVal: Array<object>;
    files: TreeNode[];

    isSelectAll: boolean = false;
    isChose: boolean = false;

    isActive = this.server.isActive;
    taskType: any = '0';
    right: any = {
        "taskPermissionList":{},
        "productList": {},
        "internalList": {},
        "themeTaskList":{}
    };

    constructor(
        private server: Service,
        public request: CudTableService,
        private tableListService: CudTableService,
        private hintsService: HintsService,
        public removeTableService: RemoveTableService,
        public initService: InitService,
        private activatedRoute: ActivatedRoute,
        private router: Router,
    ) { 
        this.right = $.extend(this.right, server.getRight());
    }

    ngOnInit() {
        this.server.eventEmit.subscribe((value: any) => {
            this.isActive = value;
        });

        this.activatedRoute.queryParams.subscribe((p: Params) => {
            this.taskType = String(p['taskType']);
            this.getTasksList();
            //权限
            if(this.taskType == '1'){
                //内文任务
                this.right['taskPermissionList'] = this.right['internalList'];
            }else if(this.taskType == '0'){
                //产品任务
                this.right['taskPermissionList'] = this.right['productList'];
            }else if(this.taskType == '2'){
                //主题词任务
                this.right['taskPermissionList'] = this.right['themeTaskList'];
            }
        });

        this.exportRefreshTableEmit = exportRefreshTable.subscribe((value: any) => {
			if(!value){
			    this.getTasksList();
			}
        })
    }

    //取消订阅
    public exportRefreshTableEmit: any;
    public productTaskTypeEmit:any;
	ngOnDestroy() {
	  if (this.exportRefreshTableEmit) {
		this.exportRefreshTableEmit.unsubscribe()
      }
      if (this.productTaskTypeEmit) {
		this.productTaskTypeEmit.unsubscribe()
	  }
    }
    
    getTasksList() {
        let params = this.getTasksListParams();
        this.request.postRequest(this.server.baseUrl +appProductUrl.getTasksList, params).then((res: any) => {
            this._cancelChecked();
            if (res.result_code === '0000') {
                this.tabVal = res.result;
                if(this.tabVal.length > 0) {
                    for(let item of this.tabVal) {
                        let themeWordTableNames = '';
                        for(let child of item['idxTaskThemeTableList']) {
                            themeWordTableNames += child['themeWordTableName'] + ' ';
                        }
                        item['themeWordTableNames'] = themeWordTableNames;

                        let taskAssignBys = '';
                        for(let child of item['idxTaskAssignList']) {
                            taskAssignBys += child['taskAssignBy'] + ' ';
                        }
                        item['taskAssignBys'] = taskAssignBys;

                    }
                }
                this.total = res.length;
                this.naturalNum = product.pagination.naturalNum;
                this.files = this._processTreeData(this.tabVal, 'taskId', 'parentId', 'name');
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    //查询参数
    private getTasksListParams() {
        return {
            token: product.retrieval.token,
            pageNo: product.pagination.pageNumber,
            pageSize: product.pagination.pageSize,
            id: product.retrieval.id,
            queryCriteria: product.retrieval.queryCriteria,
            checkStatus: product.retrieval.checkStatus,
            createBy: this.server.getuserName(),
            taskType: Number(this.taskType),
            parentId: ''
        }
    }

    _processTreeData(list: Array<any>, idName, parentIdName, labelName): Array<any> {
        return this._toTree(list, '0', idName, parentIdName, labelName);
    }

    _toTree(list: Array<any>, topId = '0', idName, parentIdName, labelName) {
        let idKey = idName;
        let result = [];
        for (let item of list) {
            if (item[parentIdName] == topId) {
                let children = {};
                let leaf = false;
                if (item['child'] == '0') {
                    leaf = true;
                }
                let dataArr = {
                    'data': item,
                    'taskId': item['taskId'],
                    'leaf': leaf
                };
                result.push(dataArr);
            }
        }
        return result;
    }

    onNodeExpand(event) {
        const node = event.node;
        let queryParams = {
            token: product.retrieval.token,
            pageNo: 1,
            pageSize: 9999,
            id: product.retrieval.id,
            queryCriteria: product.retrieval.queryCriteria,
            checkStatus: product.retrieval.checkStatus,
            createBy: this.server.getuserName(),
            taskType: this.taskType,
            parentId: node.data.taskId
        };
        this.getChildrenList(queryParams, node);
    }
    /**
     * 点击图标显示子级的任务
     * @param queryData 
     * @param node 
     */
    public getChildrenList(queryData, node) {
        this.request.postRequest(this.server.baseUrl +appProductUrl.getTasksList, queryData).then((data: any) => {
            if (data.result_code == '0000') {
                node['children'] = this._toTree(data.result, node['taskId'], 'taskId', 'parentId', 'name');
                this.files = [...this.files];
                return false;
            } else {
                this.hintsService.messages(data.message, data.result_code);
            }
        }).catch();
    }

    /**
     * 全选
     * @param bool
     * @param tabVal
     */
    _selectAll(bool, tabVal) {
        this.isSelectAll = this.isChose = this.removeTableService.removeAll(bool, tabVal, 'taskId');
    }

    /**
     * 单选
     * @param bool
     * @param taskId
     * @param length
     */
    _chose(bool, taskId, length) {
        this.isSelectAll = this.removeTableService.removeChose(bool, taskId, length)['bool'];
    }

    /**
     * 重置表格复选框、选中的ID
     */
    private _cancelChecked() {
        this.isChose = this.isSelectAll = false;
        this.removeTableService._clearId('taskId');
    }

    public setData(v: any, type) {
        if (type === 'addChildTask') {
            taskAddEimt.emit({ 'data': v, 'type': type });
        } else if (type === 'edit') {
            taskAddEimt.emit({ 'data': v, 'type': type });
        }else if (type === 'detail') {
            taskAddEimt.emit({ 'data': v, 'type': type });
        }
    }
    
}

